<template>
  <div>
    <div class="header-search-box shadow">
      <sec-form
        :searchBox="{ span: 8 }"
        :span="8"
        :ruleForm="searchForm.data"
        :optionData="searchForm.optionData"
        :formData="searchForm.config"
        @reset="getTableList(true)"
        @submitForm="getTableList(true)"
      >
      </sec-form>
    </div>

    <div class="scene-main tab-scene-main">
      <div class="new-file">
        <el-button type="primary" @click="handleNew" icon="el-icon-plus">新 建</el-button>
      </div>
      <sec-table :tableData="searchTable.rows" :tableCol="searchTable.cols" ref="secTabel">
        <template v-slot:itemList="{ data }">
          <div v-for="item in data.row.itemList" :key="item.id">
            <el-tag style="margin-bottom: 4px"> {{ item.itemName }} </el-tag><br />
          </div>
        </template>
      </sec-table>

      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page.sync="page"
        background
        :page-sizes="pageSizes"
        :page-size="pageSize"
        :layout="layout"
        :total="totalSize"
      >
      </el-pagination>
    </div>

    <el-dialog :title="title" :visible.sync="diaShow" width="60%">
      <sec-form
        ref="opForm"
        :itemRules="opForm.itemRules"
        :optionData="opForm.optionData"
        :loadingProp="opForm.loadingProp"
        :hideProp="hideProp"
        :ruleForm="opForm.ruleForm"
        :formData="opForm.formData"
        :rules="opForm.rules"
        :disabledProp="disabledProp"
      >
      </sec-form>
    </el-dialog>
  </div>
</template>

<script>
import { paginationMixin } from "common/js/mixin";
import { tagListApi, tagDeleteApi, tagSaveApi, itemListAPI, assetTagFlagApi } from "api/configApi.js";
import { allSceneApi } from "api/api.js";
export default {
  name: "evaluate",
  props: {},
  mixins: [paginationMixin],
  components: {},
  data() {
    return {
      disabledProp: {
        tagName: false,
        tagLevel: false,
      },
      hideProp: {
        itemList: true,
        sceneId: false,
      },
      status: "",
      diaShow: false,
      title: "",
      searchForm: {
        optionData: {
          tagLevel: [],
        },
        data: {
          tagName: "",
          tagLevel: [],
        },
        config: [
          {
            type: "text",
            label: "标签名称",
            prop: "tagName",
          },
          {
            type: "select",
            filterable: true,
            clearable: true,
            label: "标签级别",
            multiple: true,
            collapseTags: true,
            prop: "tagLevel",
            option: this.$store.state.dictionary[100400],
          },
        ],
      },
      searchTable: {
        cols: [
          { label: "标签名称", prop: "tagName" },
          {
            label: "标签级别",
            prop: "tagLevel",
            formatter: (row, column, cellValue, index) => {
              let ss = this.$store.state.dictionary[100400].filter((e) => e.value == cellValue);
              return Array.isArray(ss) && ss.length > 0 ? ss[0].label : "";
            },
          },
          {
            label: "是否自动化",
            prop: "auto",
            width: 100,
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel("auto", cellValue);
            },
          },
          {
            label: "标签类型",
            prop: "tagType",

            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel("tagType", cellValue);
            },
          },
          { label: "关联场景", prop: "sceneName" },
          { type: "slot", label: "关联指标", prop: "itemList", width: 200, align: "left" },
          { label: "创建人", prop: "creator" },
          { label: "创建时间", prop: "createTime", width: 150 },
          { label: "更新人", prop: "operator" },
          { label: "更新时间", prop: "modifyTime", width: 150 },
          { label: "标签备注", prop: "remark" },
          {
            label: "操作",
            prop: "operation",
            width: 150,
            children: [
              {
                title: "编辑",
                click: ({ row }) => {
                  // 判断是否关联资产
                  assetTagFlagApi({ tagCode: row.tagCode }).then((res) => {
                    let related = res.data;
                    this.disabledProp.tagName = related ? true : false;
                  });
                  row["auto"] = row.auto + "";
                  //获取选中的关联指标
                  let itemList = row.itemList.map((item) => item.itemCode);
                  row.sceneId = row.sceneId == -1 ? "" : row.sceneId;
                  this.opForm.ruleForm = { ...row, itemList: itemList };
                  this.itemListHandle(row.tagType);
                  this.diaShow = true;
                  this.$nextTick(() => {
                    this.$refs.opForm.clearValidate();
                  });
                  this.title = "编辑";
                },
              },
              {
                title: "删除",
                click: ({ row }) => {
                  // this.openMessage(row.tagCode);

                  this.utils.$confirm({ content: "是否确定删除改数据？" }, () => {
                    assetTagFlagApi({ tagCode: row.tagCode }).then((res) => {
                      if (res.data) {
                        this.openMessage(row.tagCode);
                      } else {
                        tagDeleteApi({ id: row.id, version: row.version, tagCode: row.tagCode }).then((res) => {
                          this.message.state(res);
                          this.getTableList();
                        });
                      }
                    });
                  });
                },
              },
            ],
          },
        ],
        rows: [],
      },
      opForm: {
        ruleForm: {
          tagName: "",
          sceneId: "",
          remark: "",
          auto: "",
          itemList: [],
          tagType: "data",
          tagLevel: "",
        },

        itemRules: {
          itemList: [{ required: false }],
          sceneId: [{ required: true, message: "请选择", trigger: "blur" }],
        },
        optionData: {
          sceneId: [],
          auto: this.$store.state.dictionary["auto"],
          tagType: this.$store.state.dictionary["tagType"],
          itemList: [],
        },
        rules: {
          tagName: [{ required: true, message: "请输入", trigger: "blur" }],
          tagLevel: [{ required: true, message: "请选择", trigger: "blur" }],
          sceneId: [{ required: true, message: "请选择", trigger: "blur" }],
          auto: [{ required: true, message: "请选择", trigger: "blur" }],
          tagType: [{ required: true, message: "请选择", trigger: "blur" }],
          itemList: [{ required: true, message: "请选择", trigger: "blur" }],
        },
        loadingProp: {
          save: false,
        },

        formData: [
          {
            type: "text",
            label: "标签名称",
            maxlength: 50,
            prop: "tagName",
          },
          {
            type: "select",
            label: "标签类型",
            filterable: true,
            prop: "tagType",
            change: () => {
              this.itemListHandle(this.opForm.ruleForm.tagType);
            },
          },
          {
            type: "select",
            label: "是否自动化",
            filterable: true,
            prop: "auto",
          },
          {
            type: "select",
            label: "标签级别",
            maxlength: 50,
            prop: "tagLevel",
            option: this.$store.state.dictionary[100400],
          },
          {
            type: "select",
            label: "关联场景",
            filterable: true,
            prop: "sceneId",
            optionProps: { label: "optionName", value: "sceneId" },
          },
          {
            type: "select",
            label: "关联指标",
            filterable: true,
            multiple: true,
            collapseTags: true,
            prop: "itemList",
            optionProps: { label: "itemName", value: "itemCode" },
          },
          {
            type: "textarea",
            label: "标签备注",
            prop: "remark",
          },
          {
            type: "operation",
            style: { "text-align": "right" },
            children: [
              {
                label: "保 存",
                prop: "save",
                type: "primary",
                click: () => {
                  if (this.$refs.opForm.submitForm()) {
                    this.opForm.loadingProp.save = true;
                    let { id, tagName, remark, sceneId, tagCode, version, itemList, auto, tagType, tagLevel } =
                      this.opForm.ruleForm;
                    console.log("[ itemList ] >", itemList);

                    //编辑时 获取itemList的itemCode,新建时获取itemList下form表单选中的code
                    let itemListMap = itemList.map((item) => {
                      return { itemCode: item.itemCode ? item.itemCode : item };
                    });

                    tagSaveApi({
                      id: id || "",
                      tagName: tagName,
                      remark: remark,
                      itemList: itemListMap || [],
                      auto: Number(auto),
                      tagType,
                      sceneId: sceneId,
                      tagCode: tagCode || "",
                      version: version || "",
                      tagLevel: tagLevel || "",
                    }).then((res) => {
                      this.opForm.loadingProp.save = false;
                      let state = this.message.state(res);
                      if (!state) return;
                      this.diaShow = false;
                      this.getTableList();
                    });
                  }
                },
              },
              {
                label: "取消",
                click: () => {
                  this.diaShow = false;
                },
              },
            ],
          },
        ],
      },
    };
  },
  computed: {},
  watch: {},
  mounted() {
    this.getTableList();
    this.allSceneOption(); //获取所有场景
    this.initItemList(); //获取所有指标数据
  },
  methods: {
    initItemList() {
      itemListAPI({ pageSize: 1000, pageNum: 1 }).then((res) => {
        this.opForm.optionData.itemList = [];
        let data = res.data || [];
        data.forEach((item) => {
          let obj = { itemCode: item.code, itemName: item.name };
          this.opForm.optionData.itemList.push(obj);
        });
        console.log(this.opForm.optionData.itemList);
      });
    },
    allSceneOption() {
      allSceneApi({}).then((res) => {
        this.opForm.optionData.sceneId = res.data;
      });
    },
    getTableList(paginationReset) {
      if (paginationReset) {
        this.paginationReset();
      }
      let loading = this.openLoading();
      tagListApi({
        pageNum: this.page,
        pageSize: this.pageSize,
        tagName: this.searchForm.data.tagName,
        // 标签级别传值
        tagLevels: this.searchForm.data.tagLevel,
      }).then((res) => {
        loading.close();
        this.searchTable.loading = false;
        this.totalSize = res.count;
        this.searchTable.rows = res.data;
      });
    },
    handleNew() {
      this.title = "新建";
      this.disabledProp.tagName = false;
      this.diaShow = true;
      this.$nextTick(() => {
        this.$refs.opForm?.resetForm();
        this.opForm.ruleForm.id = "";
        this.opForm.ruleForm.tagLevel = "";
        this.opForm.ruleForm.tagName = "";
        this.opForm.ruleForm.sceneId = "";
        this.opForm.ruleForm.remark = "";
        this.opForm.ruleForm.itemList = [];
        this.opForm.ruleForm.auto = "";
        this.opForm.ruleForm.tagType = "data";
        this.itemListHandle(this.opForm.ruleForm.tagType);
      });
    },
    itemListHandle(tagType) {
      //初始化逻辑
      this.opForm.ruleForm.tagLevel = "";
      this.disabledProp.tagLevel = false;
      this.hideProp.itemList = true;
      this.hideProp.sceneId = false;
      this.opForm.itemRules.sceneId = [{ required: true, message: "请选择", trigger: "blur" }];
      //特殊处理
      if (tagType == "sec") {
        this.hideProp.itemList = false;
        this.opForm.itemRules.sceneId = [{ required: false }];
      } else if (tagType == "other") {
        this.hideProp.sceneId = true;
        this.disabledProp.tagLevel = true;
        this.opForm.ruleForm.tagLevel = "general";
      }
    },
    sizeChange(val) {
      this.pageSize = val;
      this.getTableList();
    },
    currentChange(val) {
      this.page = val;
      this.getTableList();
    },

    openMessage(tagCode) {
      this.$message({
        dangerouslyUseHTMLString: true,
        showClose: true,
        message: `删除失败，该标签已关联资产，暂无法删除，点击查看<a href='${location.origin}/property/manage?tagCode=${tagCode}'><strong style='color: #409eff'>关联详情</strong></a>`,
        type: "error",
      });
    },
  },
};
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
</style>
